package report

import (
	"context"
	"io"

	"gitee.com/bjf-fhe/apicat/aggregation"
	"gitee.com/bjf-fhe/apicat/config"
	"gitee.com/bjf-fhe/apicat/entry/handler"
	"gitee.com/bjf-fhe/apicat/errors"
	"gitee.com/bjf-fhe/apicat/platform"
	"gitee.com/bjf-fhe/apicat/result"
	"gitee.com/bjf-fhe/apicat/source"
	"github.com/getkin/kin-openapi/openapi3"
	"github.com/sirupsen/logrus"
)

//执行report操作，向目标文件写入生成的html结果
func Do(rootConfig *config.Config, api *openapi3.T, baseUrl string, dest io.WriteCloser, ctx context.Context) (stat result.StatReader, err error) {
	var reader source.Reader
	ctx, cancel := context.WithCancel(ctx)

	if rootConfig.RemoteAggregationAsMain {
		reader, err = aggregation.NewServer(rootConfig.RemoteAggregationMainServer, nil, ctx)
	} else {
		reader, err = platform.GetSource(rootConfig.SourceMode, rootConfig, ctx, false)
	}

	if err != nil {
		logrus.WithError(err).Error("初始化读取源数据失败")
		cancel()
		return nil, errors.Wrap(err, errors.SourceReadError)
	} else {
		logrus.Info("初始化读取源数据成功")
	}

	var localStat *result.Stat

	if rootConfig.RemoteAggregationAsSub {
		stat, err = aggregation.NewGrpcClient(rootConfig.RemoteAggregationMainServer, ctx)
		if err != nil {
			logrus.WithError(err).Error("初始化远程汇聚客户端失败")
			cancel()
			return nil, errors.Wrap(err, errors.SourceReadError)
		}
	} else {
		localStat = result.NewStat(ctx)
		stat = localStat
	}

	logrus.Infoln("开始执行处理流程")

	var handle = handler.NewHandlers(ctx, stat)

	// if rootConfig.RemoteAggregationAsSub {
	// 	handle.HandleAsSub(reader, rootConfig, api, baseUrl)
	// } else {
	handle.Handle(reader, rootConfig, api, baseUrl)
	// }

	if rootConfig.RemoteAggregationAsSub {
		logrus.Info("已完成数据上报，请登录汇聚机查询聚合结果")
	} else {
		err = result.GenerateReport(dest, localStat, ctx)
	}

	cancel()

	return
}
